<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>企业微信信息化平台</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}">
    <link rel="stylesheet" th:href="@{/index.css}">
</head>
<body>
<div class="layui-fluid " style="max-height: calc(100vh); overflow:auto;">
    <div class="layui-tab" lay-filter="test1">
        <ul class="layui-tab-title" style="height: calc(5vh);">
            <li class="layui-this" lay-id="111">待办事项</li>
            <li lay-id="222">支持数据</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show">
                <div class="layui-fluid " style="overflow:no-display">
                    <!--        style="max-height: calc(100vh); overflow:auto;"-->
                    <div class="layui-col-md1">
                        <ul>
                            <li>
                                <form class="layui-form" lay-filter="formDemo1">
                                    <label>
                                        <select name="all_engineer" lay-verify="" lay-search lay-filter="formDemo"
                                                id="all_engineer">
                                            <option value="all_engineer">全部员工</option>
                                        </select>
                                    </label>
                                    <label for="test10">日期时间范围</label>
                                    <input type="text" class="layui-input" id="test10" style="font-size:1%">
                                </form>
                            </li>
                            <li>
                                <ul class="layui-menu" id="docDemoMenu1">
                                    <li lay-options="{type:'problem',status:0, engineer_id:'all_engineer'}">
                                        <div class="layui-menu-body-title" id="problemOn">未解决问题</div>
                                    </li>
                                    <li lay-options="{type:'message',status:0, engineer_id:'all_engineer'}">
                                        <div class="layui-menu-body-title">未响应消息</div>
                                    </li>

                                    <li lay-options="{type: 'message',status:1, engineer_id:'all_engineer'}">
                                        <div class="layui-menu-body-title">已响应消息</div>
                                    </li>
                                    <li lay-options="{type:'problem',status:1, engineer_id:'all_engineer'}">
                                        <div class="layui-menu-body-title">已解决问题</div>
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <div class="layui-panel" id="tbOverTime">
                                    <button type="button" class="layui-btn layui-btn-sm  layui-btn-danger"
                                            id="titleNeedToReply">要添加问题状态的数量
                                    </button>
                                    <table class="layui-table" lay-size="sm">
                                        <colgroup>
                                            <col>
                                        </colgroup>
                                        <thead>
                                        <tr>
                                            <th style="text-align: center ">人员</th>
                                            <th style="text-align: center ">数量</th>
                                        </tr>
                                        </thead>
                                        <tbody id="tbodyNeedAddProblemStatus">
                                        </tbody>
                                    </table>
                                </div>
                            </li>
                            <li>
                                <a th:href="@{/logout}" class="layui-btn" target="_self">登出账号</a>
                                <!--            <a th:href="@{/changePassword}" class="layui-btn" target="_blank">修改密码</a>-->
                        </ul>
                    </div>
                    <div class="layui-col-md3" style="max-height: calc(95vh); overflow:auto; ">

                        <table class="layui-table">
                            <colgroup>
                                <col>
                            </colgroup>
                            <thead>
                            <tr>
                                <th>群名</th>
                            </tr>
                            </thead>
                            <tbody id="group_list">
                            </tbody>
                        </table>
                    </div>
                    <div class="layui-col-md8 " style="max-height: calc(95vh); overflow:auto; " id="div1">
                        <div class="layui-form">
                            <div id="message_card"></div>
                            <table class="layui-table">
                                <colgroup>
                                    <col style="width: 40%">
                                    <col style="width: 4%">
                                    <col style="width: 7%">
                                    <col style="width: 4%">
                                </colgroup>
                                <thead>
                                <tr>
                                    <th id="thGroupName" style="text-align: center ">问题</th>
                                    <th>工程师</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody id="message_list">

                                </tbody>
                                <!--                <tfoot id="tFoot"></tfoot>-->
                            </table>
                        </div>
                    </div>

                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-btn-group">
                    <button type="button" class="layui-btn layui-btn-normal" id="nextMonth"
                            onclick="dataChange(this.id)">下个月
                    </button>
                    <button type="button" class="layui-btn layui-btn-normal" id="lastMonth"
                            onclick="dataChange(this.id)">上个月
                    </button>
                    <button type="button" class="layui-btn layui-btn-normal" id="startTimeBtn">开始时间</button>
                    <button type="button" class="layui-btn layui-btn-normal" id="endTimeBtn">结束时间</button>
                </div>
                <div class="page-item">
                    <label for="dateChooseEngineerData"></label>
                    <input type="text" class="layui-input" id="dateChooseEngineerData" style="font-size:1%">
                    <table class="layui-hide" id="engineerData" lay-filter="test3"></table>
                    <table class="layui-hide" id="groupData" lay-filter="test4"></table>
                </div>
            </div>
        </div>
    </div>
</div>
<script th:src="@{/layui/jquery-3.6.0.min.js}"></script>
<script th:src="@{/layui/layui.js}"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script>
    layui.use(['form'], function () {
        let form = layui.form
        $.ajax({
            url: "/sel_all_engineer",
            type: "get",
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                let engineerList = data['engineers'];
                let currentUser = data['currentUser']['name'];
                if (data != null) {
                    let selAllEngineer = document.getElementById("all_engineer");
                    for (let i = 0; i < engineerList.length; i++) {
                        selAllEngineer.innerHTML += '<option value="' + engineerList[i]['name'] + '">' + engineerList[i]['name'] + '</option>'
                    }
                    form.render('select');  //重新渲染
                    changeEngineer(currentUser);
                }
            }
        })
    })
    // 默认选择的消息类型、消息状态、工程师id(默认是全部门)、群id、群名、消息id
    let pageOptions = {
        type: "problem",
        status: "0",
        engineer_id: "all_engineer",
        cp_id: "",
        cp_name: "",
        hq: "",
        time: "0",
        endTime: '0'
    }
    let div_message_list = "<tr id='hq_id'>\n" +
        "                        <td > text</td>\n" +
        "                        <td>engineer</td>\n" +
        "                        <td>time</td>\n" +
        "                        <td>button</td>\n" +
        "                    </tr>"

    // let engineerName = '[[${engineerName}]]'/'all_engineer';
    let engineerName = $("#all_engineer option:selected").val()

    if (engineerName !== '' && engineerName !== null) {
        pageOptions.engineer_id = engineerName;
    } else {
        pageOptions.engineer_id = 'all_engineer';
    }
    let tempFormStatus = {};
    //群名列表
    let group_list = document.getElementById("group_list");
    //<button type="button"  onclick="selMsgByGroup(id,value,'待处理数量')" class="layui-btn layui-btn-normal layui-btn-fluid" id='cp_id' value='群名'>cp_name</button>
    //<span class="layui-badge layui-bg-cyan">数量</span>
    // 群名列表按钮所需单元格元素
    let div_group_msg = "<tr>\n" +
        "                    <td><button type=\"button\"  onclick=\"selMsgByGroup(id,value,'待处理数量')\" class=\"layui-btn layui-btn-normal layui-btn-fluid\" id='cp_id' value='群名'>cp_name</button></td>\n" +
        "                </tr>";
    //解决按钮所需元素
    let button_update_msg_status = "<button type=\"button\"  onclick=\"update_message_status('msg_id','engineer')\" class=\"layui-btn-sm  layui-border-black layui-btn-fluid\" >关闭</button>";
    let laypage;
    let layer;
    // {
    //     "problemAvgTime": 7663,
    //     "messageNum": 617,
    //     "messageAvgTime": 39,
    //     "sendMsgNum": 413,
    //     "problemNum": 3,
    //     "processor": "伍珈沁"
    // }
    // name: "伍珈沁"
    // proAvg: 15181
    // proCnt: 5
    // resAvg: 3545
    // resAvgW: 179
    // resCnt: 22
    // resCntW: 527
    // talkCnt: 534
    engineerData = {
        elem: '#engineerData',
        limit: 15,
        cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
        cols: [
            [
                {field: 'name', title: '员工', width: 120, sort: true}
                , {field: 'talkCnt', title: '发言数量', width: 180, sort: true}
                , {field: 'resCntW', title: '工作时间响应数量', width: 180, sort: true}
                , {field: 'resAvgW', title: '工作时间平均响应时间', width: 180, sort: true}
                , {field: 'resCnt', title: '非工作时间响应数量', width: 180, sort: true}
                , {field: 'resAvg', title: '非工作时间平均响应时间', width: 180, sort: true}
                , {field: 'proCnt', title: '问题数量', width: 180, sort: true}
                , {field: 'proAvg', title: '问题平均时间', width: 180, sort: true}

            ]
        ],
        data: [],
        // done: function (res, curr, count) {
        done: function (res) {
            let that = this.elem.next();
            res.data.forEach(function (item, index) {
                if (item.name === '部门') {
                    let tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']");
                    tr.css("background-color", "yellow");
                    console.log(item, index)
                }
            })
        }
    };
    groupData = {
        elem: '#groupData',
        limit: 15,
        cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
        cols: [
            [
                {field: 'owner', title: 'owner', width: 120, sort: true}
                , {field: 'new_chat_cnt', title: 'new_chat_cnt', width: 180, sort: true}
                , {field: 'chat_total', title: 'chat_total', width: 180, sort: true}
                , {field: 'chat_has_msg', title: 'chat_has_msg', width: 180, sort: true}
                , {field: 'new_member_cnt', title: 'new_member_cnt', width: 180, sort: true}
                , {field: 'member_total', title: 'member_total', width: 180, sort: true}
                , {field: 'member_has_msg', title: 'member_has_msg', width: 180, sort: true}
                , {field: 'msg_total', title: 'msg_total', width: 180, sort: true}

            ]
        ],
        data: []
    };
    let date = {
        month: 0,
        year: 0,
        week: 0,
        day: 0,
        optionCode: 'allDate',
        startTime: null,
        endTime: null,
        period: null
    }

    function dataChange(clickId) {
        date.optionCode = 'period';
        console.log(date)
        switch (clickId) {
            case 'nextMonth':
                date.month++;
                date["period"] = 'month';
                break;
            case 'lastMonth':
                date.month--;
                date["period"] = 'month';
                break;
            case 'nextWeek':
                if (date.period < 5) {
                    date.week++;
                    date["period"] = 'week';
                }
                break;
            case 'lastWeek':
                if (date.week > 1) {
                    date.week--;
                    date["period"] = 'week';
                }
                break;
            case 'now':

                break;
            default:
                console.log('error')
        }
        apiEngineerAvgTime(date)
    }

    function engineerAvgTime(value) {
        if (value !== null) {
            let startTime = value.substring(0, 19);
            let endTime = value.substring(22);
            let dataOption = {};
            dataOption['startTime'] = startTime;
            dataOption['endTime'] = endTime;
            dataOption['optionCode'] = 'allData'
            apiEngineerAvgTime(dataOption)
        }
    }

    function apiEngineerAvgTime(data) {
        $.ajax({
            url: "/engineerAvgTime",
            type: "get",
            data: {
                dataOption: JSON.stringify(data)
            },
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function (data) {

                addMessage(data);
            }
        })
    }

    function addMessage(data) {
        console.log(data)
        engineerData.data = data['data'];
        engineerData.limit = data['data'].length
        // let data1 = JSON.parse(data['groupData'])
        // console.log(data1)

        //返回值是否正常
        // let groupDataErrMsg = data1['errmsg'] === 'ok';


        // let groupDataList = [];

        // for (let i = 0; i < data1['items'].length; i++) {
        //     let groupDataObject = {
        //         owner: '',
        //         new_chat_cnt: '',
        //         chat_total: '',
        //         chat_has_msg: '',
        //         new_member_cnt: '',
        //         member_total: '',
        //         member_has_msg: '',
        //         msg_total: ''
        //     }
        //     groupDataObject.owner = data1['items'][i]['owner'];
        //     groupDataObject.chat_has_msg =      data1['items'][i]['data']['chat_has_msg'];
        //     groupDataObject.chat_total =        data1['items'][i]['data']['chat_total'];
        //     groupDataObject.member_has_msg =    data1['items'][i]['data']['member_has_msg'];
        //     groupDataObject.msg_total =         data1['items'][i]['data']['msg_total'];
        //     groupDataObject.new_chat_cnt =      data1['items'][i]['data']['new_chat_cnt'];
        //     groupDataObject.new_member_cnt =    data1['items'][i]['data']['new_member_cnt'];
        //     groupDataObject.member_total =      data1['items'][i]['data']['member_total'];
        //     groupDataList.push(groupDataObject)
        //     console.log(groupDataObject)
        // }
        //
        // groupData.data = groupDataErrMsg ? groupDataList : '';
        // groupData.limit = groupDataErrMsg ? groupDataList.length : '';

        let btnStartTime = document.getElementById("startTimeBtn");
        let btnEndTime = document.getElementById("endTimeBtn");
        if (data["endTime"] === null || data["startTime"] === null) {
        } else {
            btnStartTime.innerText = data["startTime"];
            btnEndTime.innerText = data["endTime"]
        }
        layui.use('table', function () {
            let table = layui.table;
            table.render(engineerData);
            // if (groupDataErrMsg) {
            //     table.render(groupData);
            // }
        });
    }

    // {"engineer_name":"","group_name":"","type":"problem","status":"all"}
    layui.use('form', function () {
        const form = layui.form;
        form.on('select(formDemo)', function (data) {
            pageOptions.engineer_id = data.value
            // console.log('选择的员工id' + pageOptions.toString()); //得到被选中的值
            ask_all_group_message(pageOptions);
            ask_all_message(pageOptions);
        });
    });
    layui.use(['laypage', 'layer'], function () {
        laypage = layui.laypage;
        layer = layui.layer;
        //完整功能
        laypage.render({
            elem: 'tFoot'
            , count: 100
            , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
            , jump: function (obj) {
                // console.log(obj)
            }
        });
    })
    layui.use('laydate', function () {
        const layDate = layui.laydate;
        let dateInfo = {
            elem: '#dateChooseEngineerData'
            , type: 'datetime'
            , range: ['#startDate', '#endDate']
            , value: '2021-08-01 00:00:00 - 2021-08-30 00:00:00'
            , trigger: 'mousedown'
            , done: function (value) {
                engineerAvgTime(value)
            }
        }
        //日期时间范围
        layDate.render(dateInfo);
        layDate.render({
            elem: '#test10'
            , type: 'datetime'
            , range: true
            , trigger: 'mousedown'
            , done: function (value) {
                let time = value.substring(0, 19)
                let endTime = value.substring(22)
                // console.log("value" + value)
                if (value !== '') {
                    pageOptions.time = Date.parse((new Date(time).toString())) / 1000
                    pageOptions.endTime = Date.parse((new Date(endTime).toString())) / 1000
                }
                // console.log(pageOptions)
                ask_all_group_message(pageOptions)
                ask_all_message(pageOptions)
            }
        });
    });

    //修改选中的员工
    function changeEngineer(name) {
        $("#all_engineer").val(name);
        pageOptions.engineer_id = name;
        // console.log('选择的员工id' + pageOptions.toString()); //得到被选中的值
        ask_all_group_message(pageOptions);
        ask_all_message(pageOptions);
        //渲染下拉框
        layui.use('form', function () {
            const form = layui.form;
            form.render("select");
        });
    }


    function BTNNameEngineer(name) {
        changeEngineer(name);
    }

    function addTbody(data, ElementId) {
        let tbModel = '<tr>\n' +
            '                    <td>\n' +
            '                        <button  class="layui-btn   layui-btn-danger layui-btn-fluid layui-btn-sm"\n' +
            '                                onclick="BTNNameEngineer(\'engineerName\')">engineer_name\n' +
            '                        </button>\n' +
            '                    </td>\n' +
            '                    <td style="text-align: center ">\n' +
            '                      problemNum  \n' +
            '                    </td>\n' +
            '                </tr>'
        let tbodyNeedAddProblemStatus = document.getElementById(ElementId)
        let temp = ''
        tbodyNeedAddProblemStatus.innerHTML = ''
        for (let i = 0; i < data.length; i++) {
            temp = tbModel.replace('engineerName', data[i]['engineer'])
            temp = temp.replace('engineer_name', data[i]['engineer']);
            if (typeof (data[i]['problemNum']) !== "undefined") {
                temp = temp.replace('problemNum', data[i]['problemNum']);
            } else if (typeof (data[i]['needToReplyNum']) !== "undefined") {
                temp = temp.replace('problemNum', data[i]['needToReplyNum']);
            }
            tbodyNeedAddProblemStatus.innerHTML += temp;
        }
    }

    function ask_allNeedAddProblemStatus_engineer() {
        $.ajax({
            url: "/selEngineerNeedAddProblemStatusCount"
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                addTbody(data, 'tbodyNeedAddProblemStatus')
            }
        })
    }

    //菜单栏事件，获取选择的消息类型与消息状态
    layui.use('dropdown', function () {
        let dropdown = layui.dropdown;
        //菜单点击事件，其中 docDemoMenu1 对应的是菜单结构上的 id 指
        dropdown.on('click(docDemoMenu1)', function (data) {
            pageOptions.type = data.type
            pageOptions.status = data.status
            document.getElementById("message_list").innerHTML = ''
            ask_all_group_message(pageOptions)
            ask_all_message(pageOptions)
            document.getElementById('thGroupName').innerText = '群名'
            let titleNeedToReply = document.getElementById('titleNeedToReply')
            if (pageOptions.status === 0) {
                if (pageOptions.type === 'problem') {

                    titleNeedToReply.innerHTML = '要添加问题状态的数量';
                    ask_allNeedAddProblemStatus_engineer();
                } else if (pageOptions.type === 'message') {
                    titleNeedToReply.innerHTML = '超时未响应的数量';
                    ask_allNeedReplyMessage();
                } else {
                }
            }
        });
    });
    layui.use('element', function () {
        const element = layui.element; //Tab的切换功能，切换事件监听等，需要依赖element模块

        //触发事件
        element.on('tab(tabChange)', function (data) {
            console.log(data);
        });
    })

    function ask_allNeedReplyMessage() {
        // console.log('超时未响应的数量')
        $.ajax({
            url: "/selEngineerNeedToReplyNum"
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                addTbody(data, "tbodyNeedAddProblemStatus")
            }
        })
    }

    function ask_all_message(options) {
        $.ajax({
            url: "/ask_all_message"
            , data: {
                data: JSON.stringify(options)
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                add_msg_list(data)
            }
        })
    }

    let form_status =
        `<div class="layui-tab" lay-filter="demo" lay-allowclose="true">
        <ul class="layui-tab-title">
            <li class="layui-this" lay-id="11">添加状态</li>
            <li lay-id="22">补充问题</li>
            <li lay-id="33">分配给其他人</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show"><table class="layui-table" style="display: none">
                    <colgroup>
                        <col style="width:300px">
                        <col style="width:100px">
                        <col style="width:100px">
                        <col>
                    </colgroup>
                    <thead>
                    <tr>
                        <th>状态</th>
                        <th>人员</th>
                        <th>时间</th>
                    </tr>
                    </thead>
                    <tbody id="tb_problem_status">tbProblemStatus
                    </tbody>
                </table>
                <textarea placeholder="请输入内容" class="layui-textarea"
                          id='addMsgStatusAreaId'></textarea>
                <button type="button" class="layui-btn layui-btn-danger" onclick="add_msg_status_content('AMSID')">更新状态</button>
            </div>
            <div class="layui-tab-item">
                <textarea placeholder="请输入内容" class="layui-textarea" id='updateTextAreaId' style='height: auto'>changeProblemContent</textarea>
                <button type="button" class="layui-btn layui-btn-danger" onclick="update_message_content('tAId')">提交修改
                </button>
            </div>
            <div class="layui-tab-item">
                changeEngineer
            </div>
        </div>
    </div>`

    //添加问题当前状态
    function add_msg_status_content(add_msg_status_content_id) {
        let addMsgStatusContentId = document.getElementById(add_msg_status_content_id)
        if (addMsgStatusContentId.value !== null && addMsgStatusContentId.value !== '') {
            let msg = {}
            msg.hq = add_msg_status_content_id.substring(3)
            msg.msgStatusContentValue = addMsgStatusContentId.value
            // msg.engineer = engineer_name
            $.ajax({
                url: "/add_problem_status"
                , data: {data: JSON.stringify(msg)}
                , type: "get"
                , dataType: "json"
                , contentType: "application/json;charset=utf-8"
                , success: function () {
                    layui.use('layer', function () {
                        layer.closeAll()
                    });
                    add_msg_status(add_msg_status_content_id.substring(3), 'engineer')
                    // updateProblemStatusTable(add_msg_status_content_id.substring(3))
                }
            })
        }

    }

    //修改问题内容
    function update_message_content(msgId) {
        let updateTextArea = document.getElementById(msgId)
        let data = {}
        data.hq = msgId.substring(7)
        data['text'] = updateTextArea.value
        $.ajax({
            url: "/change_problem"
            , data: {
                data: JSON.stringify(data)
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function () {
                layui.use('layer', function () {
                    layer.closeAll()
                });
                add_msg_status(msgId.substring(7), 'engineer')
            }
        })
    }

    function add_msg_status(msg_id, engineer) {
        updateProblemStatusTable(msg_id)
        $.ajax({
            url: "/selMsgByHq"
            , data: {
                hq: msg_id
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                // console.log(msg_by_hq)
                let msg_by_hq = data["selMsgByHq"]
                let tb_problem_status_content = data["problemStatusByHq"]
                let temp = '';
                for (let i = 0; i < tb_problem_status_content.length; i++) {
                    temp += '<tr><td>' + tb_problem_status_content[i]['statusContent']
                        + '</td><td>' + tb_problem_status_content[i]['engineer']
                        + '</td><td>' + tb_problem_status_content[i]['timeFormat']
                        + '</td></tr>'
                }
                // console.log(temp)
                // console.log(msg_by_hq, tb_problem_status_content)
                tempFormStatus = form_status.replace('changeProblemContent', msg_by_hq.text)
                tempFormStatus = tempFormStatus.replace('changeEngineer', msg_by_hq.engineer)
                tempFormStatus = tempFormStatus.replace('tAId', "update_" + msg_by_hq.hq)
                tempFormStatus = tempFormStatus.replace('updateTextAreaId', "update_" + msg_by_hq.hq)
                tempFormStatus = tempFormStatus.replace('AMSID', "add" + msg_by_hq.hq)
                tempFormStatus = tempFormStatus.replace('addMsgStatusAreaId', "add" + msg_by_hq.hq)
                // console.log(msg_by_hq["msgStatus"])
                if (temp !== "" && temp != null) {
                    tempFormStatus = tempFormStatus.replace('display: none', '')
                    // tempFormStatus = tempFormStatus.replace('tbProblemStatus', tableUpdateProblemStatus)
                    tempFormStatus = tempFormStatus.replace('tbProblemStatus', temp)
                    // tdParsing(msg_by_hq["msgStatus"])
                } else {
                    tempFormStatus = tempFormStatus.replace('tbProblemStatus', "")
                }
                layui.use('layer', function () {
                    layer.open({
                        type: 1,
                        title: false,
                        scrollbar: false,
                        content: tempFormStatus,
                        area: ['80%', '60%']
                    });
                    layui.use('form', function () {
                        const form = layui.form;
                        //表单取值
                        layui.$('#LAY-component-form-eval').on('click', function () {
                            let data = form.val('solution_input');
                            if (data['solution'] !== "") {
                                data['engineer'] = engineer
                                data['hq'] = msg_id
                                data['type'] = pageOptions.type
                                data['status'] = pageOptions.status
                                ajax_update_status(data)
                                parent.layer.closeAll()
                                layer.msg('已经解决啦');
                                document.getElementById(msg_id).innerHTML = ''
                                //关闭悬浮框
                            } else {
                                layer.msg('你还没有输入解决方案哦');
                            }
                        });
                    });
                })
            }
        })
    }

    let tableUpdateProblemStatus = ''

    function get_tableUpdateProblemStatus(data) {
        let tempTable = ''
        for (let i = 0; i < data.length; i++) {
            tempTable = tempTable + '<tr>'
            tempTable = tempTable + '<td>' + data[i]['statusContent'] + '</td>'
            tempTable = tempTable + '<td>' + data[i]['engineer'] + '</td>'
            tempTable = tempTable + '<td>' + data[i]['timeFormat'] + '</td>'
            tempTable = tempTable + '</tr>'
        }
        tableUpdateProblemStatus = tempTable
    }

    function updateProblemStatusTable(hq) {
        $.ajax({
            url: "/problemStatusByHq"
            , data: {
                hq: hq
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                get_tableUpdateProblemStatus(data)
            }
        })
    }

    let form_solution = "<form class='layui-form' lay-filter=\"solution_input\"> \n" +
        "      <textarea placeholder=\"请输入内容\" class=\"layui-textarea\" name=\"solution\"></textarea>\n" +
        "    <button type=\"button\" class=\"layui-btn layui-btn-fluid\" id=\"LAY-component-form-eval\">提交</button></form>"

    function update_problem_status(msg_id, engineer) {
        layui.use('layer', function () {
            layer.open({
                type: 1,
                title: "填写你的解决方案",
                scrollbar: false,
                content: form_solution,
                area: ['420px', '195px']
            });
            layui.use('form', function () {
                const form = layui.form;
                //表单取值
                layui.$('#LAY-component-form-eval').on('click', function () {
                    let data = form.val('solution_input');
                    if (data['solution'] !== "") {
                        data['engineer'] = engineer
                        data['hq'] = msg_id
                        data['type'] = pageOptions.type
                        data['status'] = pageOptions.status
                        ajax_update_status(data)
                        parent.layer.closeAll()
                        layer.msg('已经解决啦');
                        document.getElementById(msg_id).innerHTML = ''
                        //关闭悬浮框
                    } else {
                        layer.msg('你还没有输入解决方案哦');
                    }
                });

            });
        })
    }

    //ajax请求修改问题状态
    function ajax_update_status(options) {
        let return_data = 0
        $.ajax({
            url: "/update_msg_status"
            , data: {
                data: JSON.stringify(options)
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                // console.log(data)
                return_data = data
            }
        })
        return return_data
    }

    function update_message_status(msg_id, engineer) {
        let data = {}
        data['engineer'] = engineer
        data['hq'] = msg_id
        data['type'] = pageOptions.type
        data['status'] = pageOptions.status
        ajax_update_status(data)
        layer.msg('已经修改成功');
        document.getElementById(msg_id).innerHTML = ''
    }

    function compare(property) {
        return function (obj1, obj2) {
            const value1 = obj1[property];
            const value2 = obj2[property];
            return value1 - value2;     // 升序
        }
    }

    function ask_all_group_message(data) {
        $.ajax({
            url: "/all_group_message"
            , data: {
                data: JSON.stringify(data)
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                data.sort(compare("time"))
                add_group_info(data)
                // console.log(data)
            }
        })
    }

    function selMsgByGroup(id, cp_name, count_msg) {
        pageOptions.hq = count_msg
        pageOptions.cp_id = id
        pageOptions.cp_name = cp_name
        document.getElementById('thGroupName').innerText = cp_name
        // console.log(JSON.stringify(pageOptions))
        $.ajax({
            url: "/msg_byGroupId"
            , data: {
                data: JSON.stringify(pageOptions)
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                add_msg_list(data)
            }
        })
    }

    //向问题列表添加具体问题
    function add_msg_list(data) {
        let temp_message_list
        let messageList = document.getElementById("message_list")
        messageList.innerHTML = ''
        for (let i = 0; i < data.length; i++) {
            temp_message_list = div_message_list.replace("text", data[i]['text'])
            temp_message_list = temp_message_list.replace("engineer", data[i]['engineer'])
            temp_message_list = temp_message_list.replace("time", data[i]['admin'])
            temp_message_list = temp_message_list.replace("hq_id", data[i]['hq'])
            if (data[i]['status'] === 0) {
                //按钮
                let temp_button_update_msg_status = button_update_msg_status.replace("msg_id", data[i]['hq'])
                let temp_button_add_msg_status = button_update_msg_status.replace("msg_id", data[i]['hq'])
                temp_button_add_msg_status = temp_button_add_msg_status.replace("engineer", data[i]['engineer'])
                temp_button_add_msg_status = temp_button_add_msg_status.replace("trOnClick", 'update_message_status')
                temp_button_update_msg_status = temp_button_update_msg_status.replace("engineer", data[i]['engineer'])
                // temp_button_update_msg_status = temp_button_update_msg_status.replace("engineer", data[i])
                // pageOptions.engineer_id=data[i]['engineer']
                if (data[i]['type'] === 'message') {
                    temp_button_update_msg_status = temp_button_update_msg_status.replace("update_message_status", 'update_message_status')
                } else {
                    temp_button_update_msg_status = temp_button_update_msg_status.replace("update_message_status", 'update_problem_status')
                    temp_button_add_msg_status = temp_button_add_msg_status.replace("update_message_status", 'add_msg_status')
                    temp_button_add_msg_status = temp_button_add_msg_status.replace("关闭", '编辑')
                    temp_button_update_msg_status += temp_button_add_msg_status
                }
                temp_message_list = temp_message_list.replace("button", temp_button_update_msg_status)
                // temp_message_list = temp_message_list.replace("button", button_update_msg_status.replace("engineer", data[i]['engineer']))
            } else if (data[i]['status'] === 1) {
                if (data[i]['type'] === 'message') {
                    temp_message_list = temp_message_list.replace("button", "<br>【" + data[i]['processor'] + "】")
                } else {
                    //解决人
                    temp_message_list = temp_message_list.replace("button", data[i]['solution'] + "<br>【" + data[i]['processor'] + "】")
                }
            }
            messageList.innerHTML += temp_message_list
        }
    }

    function add_group_info(data) {
        let div_group_msg_temp;
        group_list.innerHTML = ""
        for (let i = 0; i < data.length; i++) {
            div_group_msg_temp = div_group_msg.replace("cp_name", data[i]["cpName"] + "【" + data[i]["hq"] + "】")
            div_group_msg_temp = div_group_msg_temp.replace("群名", data[i]["cpName"])
            div_group_msg_temp = div_group_msg_temp.replace("cp_id", data[i]["cpId"])
            // div_group_msg_temp = div_group_msg_temp.replace("数量", "数量" + data[i]["hq"])
            div_group_msg_temp = div_group_msg_temp.replace("待处理数量", data[i]["hq"])
            group_list.innerHTML = group_list.innerHTML + div_group_msg_temp
        }
    }

    document.getElementById('problemOn').click()
    // console.log(problemOn)
    ask_all_group_message(pageOptions)
    ask_all_message(pageOptions)
    ask_allNeedAddProblemStatus_engineer()
    dataChange('now')
</script>
</body>
</html>
